/*
 * @module: 
 * @Descripttion: 
 * @Author: guoyu
 * @Date: 2022-06-24 20:29:21
 * @LastEditors: wangshengjin
 * @LastEditTime: 2022-07-05 11:39:51
 */
const Service = require('egg').Service;
const path = require('path');
const md5 = require('md5');

/**
 * 学科subjectId
 */
const subjectMap = {
  phy: '2',
  chem: '3',
  czsw: '10',
  gzsw: '11'
}

class syncServerService extends Service {
  /**
   * @description: 更新sqlite数据库接口
   * @param {
   * type [experiment,experiment_category,knowledge_points,knowledge_experiment_map]
   * page
   * per
   * } param0 
   * @returns db
   */
  async index({ type, page = 1, per = 100 } = {}) {
    const { ctx, config } = this;
    const { baseUrl, api } = config;
    const { sync } = api;
    const now = Date.parse(new Date);
    const cet = md5(`${type}${now / 1000}`);
    const urlStr = `${baseUrl}${sync}?table=${type}&timestamp=${now / 1000}&sign=${cet}&page=${page}&per-page=${per}`;
    const res = await ctx.curl(`${urlStr}`, {
      dataType: 'json'
    });

    return res.data;
  }

  // 查询页数
  // 需要同步的表：experiment,experiment_category,knowledge_points,knowledge_experiment_map
  async create(data, type, subjectId) {
    if (type == 'experiment') {
      const imgUrl = path.basename(data.imgUrl);
      if(subjectMap.phy === subjectId) {
        data.imgUrl = `/assets/model/uploads/${imgUrl}`;
      }else if(subjectMap.chem === subjectId) {
        data.imgUrl = `libs/chem/assets/model/uploads/${imgUrl}`;
      }else if(subjectMap.czsw === subjectId) {
        data.imgUrl = `biologyres/html/cz/assets/${imgUrl}`;
      }else if(subjectMap.gzsw === subjectId) {
        data.imgUrl = `biologyres/html/gz/assets/${imgUrl}`;
      }
      return this.ctx.model.Experiment.create(data);
    } else if (type == 'experiment_category') {
      return this.ctx.model.ExperimentCategory.create(data);
    } else if (type == 'knowledge_points') {
      return this.ctx.model.KnowledgePoints.create(data);
    } else if (type == 'knowledge_emperiment_map') {
      return this.ctx.model.KnowledgeExperimentMap.create(data);
    }
  }

}

module.exports = syncServerService;
